﻿using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using System.IO;
using System.Net.Sockets;

namespace Elk232toEthernet
{
    public class Program
    {
        static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

        static string SDdirectory = @"\SD";

        public static void Main()
        {
            WebServer webServer = new WebServer();

            while (true)
            {
                webServer.WaitForRequest(new RequestReceivedDelegate(RequestReceived));
            }
        }

        private static HttpWebResponse RequestReceived(HttpWebRequest request)
        {
            request.EndRequest();

            HttpWebResponse resposne = new HttpWebResponse();

            if (request.RequestMethod == HttpWebRequest.Method.GET)
            {
                if (request.Uri.Length == 0)
                {
                    resposne.ResponseType = HttpWebResponse.ResponseTypes.FILE;
                    resposne.FileName = Path.Combine(SDdirectory, "default.htm");
                    resposne.AddHeader("HTTP/1.1 200 OK\nContent-Type: text/html\nCache-Control:no-cache\n\n");
                }
                else
                {
                    resposne.ResponseType = HttpWebResponse.ResponseTypes.FILE;
                    resposne.FileName = Path.Combine(SDdirectory, request.Uri);
                    if (resposne.FileName.Substring(resposne.FileName.Length - 3, 3) == "xap")
                    {
                        resposne.AddHeader("HTTP/1.1 200 OK\nContent-Type: application/x-silverlight-app\nCache-Control:no-cache\n\n");
                    }
                    else
                    {
                        resposne.AddHeader("HTTP/1.1 200 OK\nContent-Type: text/html\nCache-Control:no-cache\n\n");
                    }
                }
            }

            return resposne;
        }

    }
}
